import { Button, Card, CardActions, CardContent, Typography } from "@material-ui/core";
import React from "react";

export interface FileItemProps {
    name: string;
    isDirectory: boolean;
    size: number;
    modifyDate: number;

    open: (s: string, isDirectory: boolean) => void;
}

export default class FileItem extends React.Component<FileItemProps, any> {
    render() {
        let actions;
        if (this.props.isDirectory) {
            actions = (<Button onClick={() => {this.props.open(this.props.name, true)}}>Open</Button>);
        } else {
            actions = (<Button onClick={() => {this.props.open(this.props.name, false)}}>Download</Button>);
        }
        return (
        <Card>
            <CardContent>
                <Typography>{this.props.name}</Typography>
                <Typography variant={'caption'} display={'block'}>{this.toHumanReadableSize()}</Typography>
                <Typography variant={'caption'} display={'block'}>{this.toLocalTime()}</Typography>
            </CardContent>
            <CardActions>
                {actions}
            </CardActions>
        </Card>
        );
    }

    private toHumanReadableSize() {
        if (this.props.isDirectory) {
            return '-';
        }
        if (this.props.size > 1024) {
            if (this.props.size > 1024 * 1024) {
                if (this.props.size > Math.pow(1024, 3)) {
                    return (this.props.size / 1024 / 1024 / 1024).toFixed(2) + 'GiB';
                }
                return (this.props.size / 1024 / 1024).toFixed(2) + 'MiB';
            }
            return (this.props.size / 1024).toFixed(2) + 'KiB';
        }
        return this.props.size + 'B';
    }

    private toLocalTime() {
        return (new Date(this.props.modifyDate)).toLocaleString();
    }
}
